﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WP7BackupService
{
	class WcfServiceHost
	{
		ServiceHost _serviceHost;

		/// <summary>
		/// Creates the service.
		/// </summary>
		/// <returns>The service address</returns>
		public string CreateService()
		{
			try
			{
				Uri uriTcpAddress = new Uri("http://" + Settings.ServiceSettings.Ip + ":" + Settings.ServiceSettings.Port + ServiceSettings.ServiceName);
				Uri[] uriBaseAddress = { uriTcpAddress };

				_serviceHost = new ServiceHost(typeof(BackupServiceService), uriBaseAddress);

				BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
				binding.MaxBufferPoolSize = 67108864;
				binding.MaxBufferSize = 67108864;
				binding.MaxReceivedMessageSize = 67108864;
				binding.SendTimeout = TimeSpan.FromSeconds(30);
				binding.MaxReceivedMessageSize = 67108864;
				binding.ReaderQuotas.MaxArrayLength = 67108864;
				//binding.ReaderQuotas.MaxBytesPerRead = 67108864;
				binding.ReaderQuotas.MaxStringContentLength = 67108864;
				binding.TransferMode = TransferMode.Streamed;

				_serviceHost.AddServiceEndpoint(typeof(IBackupService), binding, string.Empty);

				ServiceMetadataBehavior behavior = _serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
				if (behavior == null)
				{
					behavior = new ServiceMetadataBehavior();
					behavior.HttpGetEnabled = true;
					_serviceHost.Description.Behaviors.Add(behavior);
				}

				_serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://" + Settings.ServiceSettings.Ip +":" + (Settings.ServiceSettings.Port - 1) + ServiceSettings.ServiceName + "/mex");

				_serviceHost.Open();

				return uriTcpAddress.ToString();
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex.Message);
				throw;
			}
		}

		public void CloseService()
		{
			if (_serviceHost != null && _serviceHost.State == CommunicationState.Opened)
				_serviceHost.Close();
		}
	}
}
